number++;
number--;
++number;
--number;while loopwhile (condition)
{
// statements;
}while loop is a pretest loop, which means that it’ll test the value of the condition before executing the loop.while loop executes 0 or more times.while Loop for Input ValidationSystem.out.print("Enter a number in the range of 1 through 100: ");
number = keyboard.nextInt();
// Validate the input.
while (number < 1 || number > 100)
{
System.out.println("That number is invalid.");
System.out.print("Enter a number in the range of 1 through 100: ");
number = keyboard.nextInt();
}nextLine with Calls to Other Scanner MethodsString’s nextInt, nextDouble and next methods don’t consume the newline character, causing the newline to be consumed by whatever reads System.in next.
nextLine and other methods than consume newlinesE.g.,
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Enter your city: ");
String city = scanner.nextLine();
System.out.println("Hi " + name + ", your age is " + age + " and your city is " + city);Hi John, your age is 10 and your city isFix:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.println("Enter your city: ");
String city = scanner.nextLine();
System.out.println("Hi " + name + ", your age is " + age + " and your city is " + city);Hi John, your age is 10 and your city is PomonaThe do-while Loop
do
{
// statements;
}
while (condition);do-while is a posttest loop, which means it’ll execute the loop before testing the condition.do-while loop will always perform at least one iteration.for Loopfor (initialization; test; update)
{
// statement
}Note: The
forloop is a pre-test loop
Two Categories of Loops:
while, do-whiledouble runningTotalSales = 0.0; // Accumulator (Running Total)
double sales = 0.0;
while (sales != -1) // Sentinel value
{
totalSales += sales;
sales = scanner.nextDouble();
}break and continue Statementsbreak can be used to terminate a loopcontinue will cause the currently executing iteration of a loop to terminate and the next iteration to beginImportant:
breakandcontinuebypass normal mechanisms and can make code hard to read & maintain—use only when needed
while:
do-while
for:
while if there is some type of counting variable involvedRandom classimport java.util.Random;
Random randomNumbers = new Random();nextDouble(): Return random double within 0.0 and 1.0nextFloat: Returns random float within 0.0 and 1.0nextInt: Returns random int within range of int (-2,147,483,648, 2,147,483,648)nextInt(int n): Returns random int with range of 0 to n-1nextLong(): Returns random long within range of long (-9,223,372,036,854,775,808, 9,223,372,036,854,775,808)